#!/bin/bash
# NOTE: This build is NOT a fork BUT it does use a custom native library repo for the arm64/armhf builds, which is necessary as microsoft and the multimc5 devs do not provide arm64/armhf native libraries

DIRECTORY="$(dirname "$(dirname "$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )")")"

# obtain model name
if [[ -d /system/app/ && -d /system/priv-app ]]; then
    model="$(getprop ro.product.brand) $(getprop ro.product.model)"

elif [[ -f /sys/devices/virtual/dmi/id/product_name ||
        -f /sys/devices/virtual/dmi/id/product_version ]]; then
    model="$(tr -d '\0' < /sys/devices/virtual/dmi/id/product_name)"
    model+=" $(tr -d '\0' < /sys/devices/virtual/dmi/id/product_version)"

elif [[ -f /sys/firmware/devicetree/base/model ]]; then
    model="$(tr -d '\0' < /sys/firmware/devicetree/base/model)"

elif [[ -f /tmp/sysinfo/model ]]; then
    model="$(tr -d '\0' < /tmp/sysinfo/model)"
fi
# Remove dummy OEM info.
model=${model//To be filled by O.E.M.}
model=${model//To Be Filled*}
model=${model//OEM*}
model=${model//Not Applicable}
model=${model//System Product Name}
model=${model//System Version}
model=${model//Undefined}
model=${model//Default string}
model=${model//Not Specified}
model=${model//Type1ProductConfigId}
model=${model//INVALID}
model=${model//All Series}
model=${model//�}

# adapted/inspired from retropie setup script system.sh https://github.com/RetroPie/RetroPie-Setup/blob/master/scriptmodules/system.sh
# armbian uses a minimal shell script replacement for lsb_release with basic
# parameter parsing that requires the arguments split rather than using -sidrc
mapfile -t os < <(lsb_release -s -i -d -r -c)
__os_id="${os[0]}"
__os_desc="${os[1]}"
__os_release="${os[2]}"
__os_codename="${os[3]}"

#to set $arch variable
source "${DIRECTORY}/api" || error "failed to source ${DIRECTORY}/api"

status "Installing Necessary Dependencies"
case "$__os_id" in
    Raspbian|Debian)
        case "$__os_codename" in
            bullseye|buster|stretch|jessie)
                install_packages wget apt-transport-https gnupg || error "Failed to install dependencies"
                hash -r
                cd /tmp
                rm -rf public
                rm -rf adoptopenjdk-keyring.gpg
                wget https://adoptopenjdk.jfrog.io/adoptopenjdk/api/gpg/key/public
                gpg --no-default-keyring --keyring ./adoptopenjdk-keyring.gpg --import public
                gpg --no-default-keyring --keyring ./adoptopenjdk-keyring.gpg --export --output adoptopenjdk-archive-keyring.gpg 
                rm -rf public
                rm -rf adoptopenjdk-keyring.gpg
                sudo mv adoptopenjdk-archive-keyring.gpg /usr/share/keyrings
                cd ~
                echo "deb [signed-by=/usr/share/keyrings/adoptopenjdk-archive-keyring.gpg] https://adoptopenjdk.jfrog.io/adoptopenjdk/deb $__os_codename main" | sudo tee /etc/apt/sources.list.d/adoptopenjdk.list
                ;;
            *)
                error "Debian version ($__os_codename) is too old, update to debian Jessie or newer"
                ;;
        esac
        # install dependencies
        # for now don't install openjdk-8-jre on debian based 32bit installs... the repo versions (from adoptopenjdk and raspbian) are broken and don't work
        # refer to the below bug reports for updates
        # https://bugs.launchpad.net/raspbian/+bug/1944774
        # https://github.com/adoptium/adoptium-support/issues/368

        # download java 8 from adoptium github tar.gz as a workaround
        case "$arch" in
            "64")
                install_packages build-essential libopenal1 x11-xserver-utils subversion git clang cmake curl zlib1g-dev openjdk-11-jdk adoptopenjdk-16-hotspot-jre qtbase5-dev || error "Failed to install dependencies"
                hash -r
                mkdir -p ~/MultiMC/install/java || exit 1
                cd ~/MultiMC/install/java || exit 1
                rm -rf jdk8u302-b08
                rm -rf java-8-temurin-aarch64
                rm -rf OpenJDK8U-jdk_aarch64_linux_hotspot_8u302b08.tar.gz
                wget https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u302-b08/OpenJDK8U-jdk_aarch64_linux_hotspot_8u302b08.tar.gz && tar -xzf OpenJDK8U-jdk_aarch64_linux_hotspot_8u302b08.tar.gz
                mv jdk8u302-b08 java-8-temurin-aarch64
                rm -rf OpenJDK8U-jdk_aarch64_linux_hotspot_8u302b08.tar.gz
                # check if java is working and remove if broken
                ./java-8-temurin-aarch64/bin/java -version || ( warning "The downloaded java 8 version does not work, removing it now..." && warning "It is up to you to download and install a working java 8 version." && echo "" && warning "Continuing the MultiMC5 Install without Java 8" && rm -rf java-8-temurin-aarch64 )
                cd ~
                ;;
            "32") 
                install_packages build-essential libopenal1 x11-xserver-utils subversion git clang cmake curl zlib1g-dev openjdk-11-jdk adoptopenjdk-16-hotspot-jre qtbase5-dev || error "Failed to install dependencies"
                hash -r
                mkdir -p ~/MultiMC/install/java || exit 1
                cd ~/MultiMC/install/java || exit 1
                rm -rf jdk8u302-b08-aarch32-20210726
                rm -rf java-8-temurin-armhf
                rm -rf OpenJDK8U-jdk_arm_linux_hotspot_8u302b08.tar.gz
                wget https://github.com/adoptium/temurin8-binaries/releases/download/jdk8u302-b08/OpenJDK8U-jdk_arm_linux_hotspot_8u302b08.tar.gz && tar -xzf OpenJDK8U-jdk_arm_linux_hotspot_8u302b08.tar.gz
                mv jdk8u302-b08-aarch32-20210726 java-8-temurin-armhf
                rm -rf OpenJDK8U-jdk_arm_linux_hotspot_8u302b08.tar.gz
                # check if java is working and remove if broken
                ./java-8-temurin-armhf/bin/java -version || ( warning "The downloaded java 8 version does not work, removing it now..." && warning "It is up to you to download and install a working java 8 version." && echo "" && warning "Continuing the MultiMC5 Install without Java 8" && rm -rf java-8-temurin-armhf )
                cd ~
                ;;
            *) error "Failed to detect OS CPU architecture! Something is very wrong." ;;
        esac
        ;;
    LinuxMint|Linuxmint|Ubuntu|[Nn]eon|Pop|Zorin|[eE]lementary)
        # get the $DISTRIB_RELEASE and $DISTRIB_CODENAME first from lsb-release (for ubuntu) and then from the upstream for derivatives
        source /etc/lsb-release
        source /etc/upstream-release/lsb-release
        case "$DISTRIB_CODENAME" in
            bionic|focal|groovy)
                ppa_added=$(grep ^ /etc/apt/sources.list /etc/apt/sources.list.d/* | grep -v list.save | grep -v deb-src | grep deb | grep openjdk-r | wc -l)
                if [[ $ppa_added -eq "1" ]]; then
                    status "Skipping OpenJDK PPA, already added"
                else
                    install_packages software-properties-common || error "Failed to install dependencies"
                    hash -r
                    status "Adding OpenJDK PPA, needed for Minecraft 1.17+"
                    sudo add-apt-repository ppa:openjdk-r/ppa -y
                    sudo apt update
                fi
                ;;
            *)
                requiredver="18.04"
                if printf '%s\n' "$requiredver" "$DISTRIB_RELEASE" | sort -CV; then
                    status "Skipping OpenJDK PPA, $DISTRIB_CODENAME already has openjdk-16 in the default repositories"
                else
                    error "$DISTRIB_CODENAME appears to be too old to run/compile MultiMC5"
                fi
                ;;

        esac
        # install dependencies
        install_packages build-essential libopenal1 x11-xserver-utils git clang cmake curl zlib1g-dev openjdk-8-jre openjdk-11-jdk openjdk-16-jre qtbase5-dev || error "Failed to install dependencies"
        hash -r
        ;;
    *)
        error "$__os_id appears to be an unsupported OS"
        ;;
esac

# make all the folders
cd ~
mkdir -p ~/MultiMC
cd ~/MultiMC || exit 1
mkdir -p build
mkdir -p install

# clone the complete source
status "Downloading the MultiMC5 Source Code"
git clone --recursive https://github.com/MultiMC/Launcher.git src # You can clone from MultiMC's main repo, no need to use a fork.
cd src
git remote set-url origin https://github.com/MultiMC/Launcher.git
git checkout --recurse-submodules develop || error "Could not checkout develop branch"
git pull --recurse-submodules || error "Could Not Pull Latest MultiMC Source Code, verify your ~/MultiMC/src directory hasn't been modified. You can detete the  ~/MultiMC/src folder to attempt to fix this error."
git checkout --recurse-submodules 6f6c9c6f6848f4167410eedc65e309d0231cf37d || error "Could Not Checkout MultiMC Source Code commit, verify your ~/MultiMC/src directory hasn't been modified. You can detete the  ~/MultiMC/src folder to attempt to fix this error."

# add secrets files
mkdir -p secrets
tee secrets/Secrets.h <<'EOF' >>/dev/null
#pragma once
#include <QString>
#include <cstdint>
namespace Secrets {
bool hasMSAClientID();
QString getMSAClientID(uint8_t separator);
}
EOF

tee secrets/Secrets.cpp <<'EOF' >>/dev/null
#include "Secrets.h"
#include <array>
#include <cstdio>
namespace Secrets {
bool hasMSAClientID() {
    return true;
}
QString getMSAClientID(uint8_t separator) {
    return "81a207c0-a53c-46a3-be07-57d2b28c1643";
}
}
EOF

tee secrets/CMakeLists.txt <<'EOF' >>/dev/null
add_library(secrets STATIC Secrets.cpp Secrets.h)
target_link_libraries(secrets Qt5::Core)
target_compile_definitions(secrets PUBLIC -DEMBED_SECRETS)
target_include_directories(secrets PUBLIC .)

set(Launcher_CommonName "MultiMC")

set(Launcher_Copyright "MultiMC Contributors" PARENT_SCOPE)
set(Launcher_Domain "multimc.org" PARENT_SCOPE)
set(Launcher_Name "${Launcher_CommonName}" PARENT_SCOPE)
set(Launcher_DisplayName "${Launcher_CommonName} 5" PARENT_SCOPE)
set(Launcher_UserAgent "${Launcher_CommonName}/5.0" PARENT_SCOPE)
set(Launcher_ConfigFile "multimc.cfg" PARENT_SCOPE)
set(Launcher_Git "https://github.com/MultiMC/Launcher" PARENT_SCOPE)

set(Launcher_Branding_ICNS "notsecrets/Launcher.icns" PARENT_SCOPE)
set(Launcher_Branding_WindowsRC "notsecrets/launcher.rc" PARENT_SCOPE)
set(Launcher_Branding_LogoQRC "notsecrets/logo.qrc" PARENT_SCOPE)
EOF

cd ..
# configure the project
cd build

# temporary hotfix to build with java 8 (build currently fails on java 16 autodetection)
# https://github.com/MultiMC/MultiMC5/issues/3949
# remove cmake cache until bug is fixed
rm -rf CMakeCache.txt
status "Generating the CMake File"
case "$arch" in
    "64") cmake -DLauncher_EMBED_SECRETS=ON -DJAVA_HOME='/usr/lib/jvm/java-11-openjdk-arm64' -DLauncher_BUILD_PLATFORM="$model" -DLauncher_BUG_TRACKER_URL="https://github.com/Botspot/pi-apps/issues" -DLauncher_SUBREDDIT_URL="https://www.reddit.com/r/MultiMC/" -DLauncher_DISCORD_URL="https://discord.gg/multimc"  -DCMAKE_INSTALL_PREFIX=../install -DLauncher_META_URL:STRING="https://raw.githubusercontent.com/theofficialgman/meta-multimc/master-clean/index.json" ../src || error "cmake failed to generate" ;;
    "32") cmake -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DLauncher_EMBED_SECRETS=ON -DJAVA_HOME='/usr/lib/jvm/java-11-openjdk-armhf' -DLauncher_BUILD_PLATFORM="$model" -DLauncher_BUG_TRACKER_URL="https://github.com/Botspot/pi-apps/issues" -DLauncher_SUBREDDIT_URL="https://www.reddit.com/r/MultiMC/" -DLauncher_DISCORD_URL="https://discord.gg/multimc"  -DCMAKE_INSTALL_PREFIX=../install -DLauncher_META_URL:STRING="https://raw.githubusercontent.com/theofficialgman/meta-multimc/master-clean-arm32/index.json" ../src || error "cmake failed to generate" ;;
    *) error "Failed to detect OS CPU architecture! Something is very wrong." ;;
esac

# build & install (use -j with the number of cores your CPU has)
status "Starting Compilation"
make -j$(nproc) install || error "Make install failed"

cd
mkdir -p  ~/.local/share/applications
mkdir -p  ~/.local/share/icons/MultiMC
# copy icon to .local folder
cp "${DIRECTORY}/apps/Minecraft Java MultiMC5/icon-64.png" "$HOME/.local/share/icons/MultiMC/icon-64.png"

# detect if script is running on RPi and if so override MESA GL Version
if grep -iE 'raspberry' <<< $model > /dev/null; then
    warning "You are running a Raspberry Pi, note that OpenGL 3.3 is not fully supported but it necessary to run Minecraft 1.17+."
    warning "Vannilla 1.17.1 and 1.17 have been tested to work but there is no guarantee that future versions and rendering mods will continute to work"
    sh -c "cat > ~/.local/share/applications/MultiMC.desktop << _EOF_
[Desktop Entry]
Type=Application
Exec=env MESA_GL_VERSION_OVERRIDE=3.3 QT_AUTO_SCREEN_SCALE_FACTOR=0 $HOME/MultiMC/install/MultiMC
Hidden=false
NoDisplay=false
Name=MultiMC
Icon=$HOME/.local/share/icons/MultiMC/icon-64.png
Categories=Game
_EOF_"
else
    sh -c "cat > ~/.local/share/applications/MultiMC.desktop << _EOF_
[Desktop Entry]
Type=Application
Exec=$HOME/MultiMC/install/MultiMC
Hidden=false
NoDisplay=false
Name=MultiMC
Icon=$HOME/.local/share/icons/MultiMC/icon-64.png
Categories=Game
_EOF_"
fi

status_green 'Installation is now done! You can open the launcher by going to Menu > Games > MultiMC'

warning "MultiMC5 does not give support for custom builds"
warning "Only bugs that can be reproduced on official MultiMC5 builds should be posted to https://github.com/MultiMC/MultiMC5/issues"
warning "Bugs which only appear on this build should be posted to https://github.com/Botspot/pi-apps/issues or ask for help in the Discord Server"

status "Make sure to visit the MultiMC5 wiki if this is your first time using the launcher: https://github.com/MultiMC/MultiMC5/wiki"
status "If you need help installing Optifine: https://github.com/MultiMC/MultiMC5/wiki/MultiMC-and-OptiFine"
